package data.clientdata;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;


import po.ClientPO;
import data.databaseutility.Log;
import dataservice.clientdataservice.ClientDataService;

public class ClientDataController implements ClientDataService{
	HashMap<String , ClientPO> clientList;
	
	public ClientDataController(){
		super();
		init();
	}

	public boolean Insert(ClientPO po) {
		// TODO Auto-generated method stub
		if (clientList.containsKey(po.getNum())) {
			return false;
		}
		else {
			clientList.put(po.getNum(), po);
			return true;
		}
	}

	public void delete(String num) {
		// TODO Auto-generated method stub
		ClientPO clientPO = findByNum(num);
		clientList.remove(clientPO);
	}

	public void update(ClientPO po) {
		// TODO Auto-generated method stub
		clientList.put(po.getNum(), po);
	}

	public ClientPO findByNum(String num) {
		// TODO Auto-generated method stub
		return clientList.get(num);
	}

	public ArrayList<ClientPO> findByKey(String key) {
		// TODO Auto-generated method stub
		if (clientList.size() == 0) {
			return null;
		}
		ArrayList<ClientPO> clientPOs = new ArrayList<ClientPO>();
		Iterator iterator = clientList.entrySet().iterator();
		while (iterator.hasNext()) {
			java.util.Map.Entry entry = (java.util.Map.Entry) iterator.next();
			ClientPO po = (ClientPO) entry.getValue();
			if (po.getAddress().contains(key)||
				po.getDefaultSalesman().contains(key)||
				po.getClassification().toString().contains(key)||
				po.getEmail().contains(key)||
				po.getLevel().toString().contains(key)||
				po.getName().contains(key)||
				po.getTelephone().contains(key)
				) {
				clientPOs.add(po);
			}
		}
		return clientPOs;
	}

	public void init() {
		// TODO Auto-generated method stub
		File storeFile = new File("clients.ser");
		try{
			if (storeFile.exists()) {
				FileInputStream store =  new FileInputStream(storeFile);
				ObjectInputStream hasStore = new ObjectInputStream(store);	
				hasStore.close();
			}else {
				storeFile.createNewFile();//不存在就创建一个
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void finish() {
		// TODO Auto-generated method stub
		
	}

	public void writeLog(String content) {
		// TODO Auto-generated method stub
		Log.writeLog(content);
	}

	public ArrayList<ClientPO> getClientList() {
		// TODO Auto-generated method stub
		
		ArrayList<ClientPO> clientPOs = new ArrayList<ClientPO>();
		Iterator iterator = clientList.entrySet().iterator();
		while (iterator.hasNext()) {
			java.util.Map.Entry entry = (java.util.Map.Entry) iterator.next();
			clientPOs.add((ClientPO)entry.getValue());
		}
		return clientPOs;
	}

}
